package com.atguigu.yygh.msm.controller;

import com.alibaba.excel.util.StringUtils;
import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.msm.service.MsmService;
import com.atguigu.yygh.msm.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName MsmApiController
 * @Description: 类描述
 * @Author: admin
 * @CreateDate: 2024/6/18 19:31
 * @UpdateUser: 更新人
 * @UpdateDate: 2024/6/18 19:31
 * @UpdateRemark: 更新的信息
 * @Version: 1.0
 */

@RestController
@RequestMapping("/api/msm")
public class MsmApiController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable("phone") String phone) {
        //redis中获取验证码，如果有，则直接返回ok
        //key: phone(手机号)
        //value: code(验证码）
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        //如果没有，则生成验证码，(通过阿里云)发送短信，存入redis并设置过期时间，返回ok
        code = RandomUtil.getSixBitRandom();
        //调用service层发送短信
        boolean isSend = msmService.send(phone, code);
        //判断是否发送成功
        if (isSend) {
            //存入redis并设置过期时间, 2分钟,TimeUnit.MINUTES是时间单位
            redisTemplate.opsForValue().set(phone, code, 2, TimeUnit.MINUTES);
            return Result.ok();
        } else {
            return Result.fail("短信发送失败");
        }
    }
}
